package com.ocn.li.scmdy.modules.app.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ocn.li.scmdy.common.exception.MyException;
import com.ocn.li.scmdy.common.utils.FjqJwtUtil;
import com.ocn.li.scmdy.modules.app.annotation.Login;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TODO app端认证授权拦截器,基于token
 *
 * @author crazypenguin
 * @version 1.0.0
 * @createdate 2019/1/2
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private FjqJwtUtil fjqJwtUtil;

    public static final String ACCOUNT_ID_KEY = "accountId";
    public static final String ACCOUNT_NAME_KEY = "accountName";
    public static final String DATA_AREA_CODE_KEY = "dataAreaCode";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }
        if(annotation == null){
            return true;
        }
        //获取用户凭证
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        // 凭证为空
        if(StringUtils.isBlank(token)){
            throw new MyException("token"+ "不能为空", HttpStatus.UNAUTHORIZED.value());
        }

        Claims claims = fjqJwtUtil.getClaimByToken(token);
        if(claims == null || fjqJwtUtil.isTokenExpired(claims.getExpiration())){
            throw new MyException("token" + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }

        //设置accountId到request里，后续根据accountId，获取用户信息
        String jsonStr = JSONObject.toJSONString(claims);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        System.out.println("只要加了@login注解的，都会经过这个切面输出一下jwt封装的内容---线上记得注释----" + JSONObject.toJSON(claims));
        request.setAttribute(ACCOUNT_ID_KEY, jsonObject.get("accountId"));
        request.setAttribute(ACCOUNT_NAME_KEY, jsonObject.get("accountName"));
        request.setAttribute(DATA_AREA_CODE_KEY, jsonObject.get("dataAreaCode"));
        return true;
    }
}
